package com.cc.utils;


import com.cc.config.DataBaseConfiguration;
import com.cc.config.YamlOtherConfiguration;
import com.cc.utils.beanUtil.BeanUtils;
import com.mysql.cj.jdbc.exceptions.CommunicationsException;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.util.HashMap;

@Slf4j
public class JDBCUtils {

  static HashMap<String, String> cacheData;
  private static Connection connection = null;
  private static String dataBaseName = null;

  //初始化读取数据库
  static {
    try {
      DataBaseConfiguration dataBaseConfiguration = BeanUtils.getBean(DataBaseConfiguration.class);
      initCacheData(dataBaseConfiguration.getUrl(), dataBaseConfiguration.getUsername(), dataBaseConfiguration.getPassword(), BeanUtils.getBean(YamlOtherConfiguration.class).getDataBaseName());
      connection = DriverManager.getConnection(cacheData.get("url"), cacheData.get("username"), cacheData.get("password"));
      dataBaseName = cacheData.get("dataBaseName");
      log.info("当前数据库为：" + cacheData.get("dataBaseName"));
    } catch (SQLException e) {
      log.info(e.toString());
      throw new RuntimeException(e);
    }
  }

  private static void reloadCache(String address, String username, String password, String dataBaseName) {
    String template = "jdbc:mysql://${address}/${databasename}?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=true&verifyServerCertificate=false&requireSSL=true";
    cacheData = new HashMap<>();
    String url = template.replace("${address}", address).replace("${databasename}", dataBaseName);
    cacheData.put("url", url);
    cacheData.put("username", username);
    cacheData.put("password", password);
    cacheData.put("dataBaseName", dataBaseName);
  }

  private static void initCacheData(String url, String username, String password, String dataBaseName) {
    cacheData = new HashMap<>();
    cacheData.put("url", url);
    cacheData.put("username", username);
    cacheData.put("password", password);
    cacheData.put("dataBaseName", dataBaseName);
  }

  public static Connection getConnection() {
    return connection;
  }

  public static String getDataBaseName() {
    return "'" + dataBaseName + "'";
  }

  /**
   * 老方法
   * 通过修改target的方式修改
   *
   * @author C.c
   * @since 2023-05-19 14:03
   **/
  public static void reload() throws SQLException {
    DataBaseConfiguration dataBaseConfiguration = BeanUtils.getBean(DataBaseConfiguration.class);
//    connection = DriverManager.getConnection(dataBaseConfiguration.getUrl(), dataBaseConfiguration.getUsername(), dataBaseConfiguration.getPassword());
//    dataBaseName = BeanUtils.getBean(YamlOtherConfiguration.class).getDataBaseName();
    connection = DriverManager.getConnection(cacheData.get("url"), cacheData.get("username"), cacheData.get("password"));
    dataBaseName = cacheData.get("dataBaseName");
    log.info("当前数据库为：" + cacheData.get("dataBaseName"));
  }

  /**
   * 通过修改缓存
   * 通过修改target的方式修改
   *
   * @author C.c
   * @since 2023-05-19 14:03
   **/
  public static void reload(String address, String username, String password, String dataBase) {
    reloadCache(address, username, password, dataBase);
    try {
      connection = DriverManager.getConnection(cacheData.get("url"), cacheData.get("username"), cacheData.get("password"));
    } catch (CommunicationsException e) {
      throw new RuntimeException("url地址错误！！请检查！！");
    } catch (SQLSyntaxErrorException e) {
      throw new RuntimeException(e.getMessage());
    } catch (SQLException e) {
      throw new RuntimeException("数据库密码或账号错误！！请检查！！");
    }
    dataBaseName = cacheData.get("dataBaseName");
  }

  public static boolean isConnection() {
//    try {
//      reload();
//    } catch (CommunicationsException e) {
//      throw new RuntimeException("url地址错误！！请检查！！");
//    } catch (SQLSyntaxErrorException e) {
//      throw new RuntimeException(e.getMessage());
//    } catch (SQLException e) {
//      throw new RuntimeException("数据库密码或账号错误！！请检查！！");
//    }

    try {
      if (!connection.isClosed()) {
        String sql = "select * from information_schema.COLUMNS WHERE TABLE_SCHEMA = " + getDataBaseName();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
          return true;
        }
        return false;
      }
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
    return false;
  }

  public static String getAddress() {
    String[] urls = cacheData.get("url").split("//");
    String[] split = urls[1].split("/");
    return split[0];
  }
}
